package com.common.report.service;

import java.awt.Color;
import java.awt.Font;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.xml.rpc.ServiceException;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;

import com.common.base.BaseService;
import com.common.jdbc.DB4ObjUtil;
import com.common.jdbc.DBBaseUtil;
import com.common.jdbc.DBSource;
import com.common.report.vo.ReportDataVO;
import com.common.report.vo.ReportSingleSerChartVO;
import com.common.report.vo.ReportSingleSerDataVO;
import com.common.report.vo.ReportSumDataVO;
import com.common.report.vo.ReportTableViewVO;
import com.common.report.vo.ReportTitleVO;
import com.common.util.StringUtil;

/**
 * <li>@类说明: 
 * <li>@创建人:王剑 
 * <li>@创建日期:2009-3-18 
 */
public abstract class ReportService extends BaseService {
	protected String startDate = "";
	protected String endDate = "";
	protected String year = "";
	protected String yearMonth = "";

	protected String dateType;
	protected String date = "";
	public String getDateType() {
		return dateType;
	}

	public void setDateType(String dateType) {
		this.dateType = dateType;
	}
	public List findDatesByType(String type,String date){
		List<ReportDataVO> list = new ArrayList<ReportDataVO>();
		log.info("type=========="+type+"======date==="+date);
		String sql = "select * from REPORT_TABLE where type=? and sqlwhere=?";
		list  = DB4ObjUtil.execute4Obj(new ReportDataVO(), sql, type,date);
		
		
		return list;
	}
	public List saveDates(List<ReportDataVO> list,String type,String sqlwhere){
		
		String sql = "insert into REPORT_TABLE(TITLES,MENTS,COUNTS,TYPE,SQLWHERE)values(?,?,?,?,?)";
		Connection conn = DBSource.getConnection();
		try {
		conn.setAutoCommit(false);
		for (int i = 0; i < list.size(); i++) {
			ReportDataVO v= list.get(i);
			DBBaseUtil.executeUpdateByConn(conn, sql, v.getTitles(),v.getMents(),v.getCounts(),type,sqlwhere);
		}
			conn.commit();
		} catch (SQLException e) {
			log.error(e.getMessage(),e);
			try {
				conn.rollback();
			} catch (SQLException e1) {
				log.warn(e.getMessage(),e);
			}
		}finally{
			try {
				conn.close();
			} catch (SQLException e) {
				log.warn(e.getMessage(),e);
			}
		}
		
		return list;
	}
	/**
	 * <li>@方法说明:获得柱状图jfreechart对象
	 * <li>@param reportVO
	 * <li>@return
	 * <li>@创建人:王剑
	 * <li>@创建日期:2010-7-26
	 * <li>@修改人: 
	 * <li>@修改日期:
	 * <li>@详细说明: 
	 */
	public static JFreeChart getBarChart(ReportSingleSerChartVO reportVO){
		Font font = new Font("宋体",Font.PLAIN,13);
		DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
		for (int i = 0; i <reportVO.getDataList().size(); i++) {
			ReportSingleSerDataVO dataVO =reportVO.getDataList().get(i);
			dataSet.setValue(StringUtil.Str3Num(dataVO.getValue()),dataVO.getSeriesName(),dataVO.getLabel() );
		}
		JFreeChart chart = ChartFactory.createBarChart3D(reportVO.getReportName(), reportVO.getXAxisName(),reportVO.getYAxisName(), dataSet,PlotOrientation.VERTICAL,true,true,false);
		chart.setTitle(new TextTitle(chart.getTitle().getText(),new Font("宋体",Font.PLAIN,20)));
		chart.getLegend().setItemFont(font);
		
		CategoryPlot plot = (CategoryPlot)chart.getPlot();
		plot.setNoDataMessage("无统计数据");
		
		CategoryAxis domainAxis = plot.getDomainAxis();  
		domainAxis.setLabelFont(font); 
		domainAxis.setTickLabelFont(font); 
		domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
		
		ValueAxis rangeAxis = plot.getRangeAxis();
		rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); 
		rangeAxis.setLabelFont(font);
		rangeAxis.setTickLabelFont(font);
		
		BarRenderer renderer=(BarRenderer)plot.getRenderer();
		
		//renderer.setSeriesPaint(0,Color.green);
		renderer.setItemLabelsVisible(true);
		renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
		renderer.setMaximumBarWidth(0.03f);
		renderer.setItemMargin(0.0f);
		return chart;
	}
	
	/**
	 * <li>@方法说明:获得折线图JFREECHART对象
	 * <li>@param reportVO
	 * <li>@return
	 * <li>@创建人:王剑
	 * <li>@创建日期:2010-7-26
	 * <li>@修改人: 
	 * <li>@修改日期:
	 * <li>@详细说明: 
	 */
	public static JFreeChart getLineChart(ReportSingleSerChartVO reportVO){
		Font font = new Font("宋体",Font.PLAIN,13);
		DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
		for (int i = 0; i <reportVO.getDataList().size(); i++) {
			ReportSingleSerDataVO dataVO =reportVO.getDataList().get(i);
			dataSet.setValue(StringUtil.Str3Num(dataVO.getValue()),dataVO.getSeriesName(),dataVO.getLabel() );
		}
		JFreeChart chart = ChartFactory.createLineChart(reportVO.getReportName(),reportVO.getXAxisName(), reportVO.getYAxisName(), dataSet,PlotOrientation.VERTICAL,true,true,false);
		chart.setTitle(new TextTitle(chart.getTitle().getText(),new Font("宋体",Font.PLAIN,20)));
		chart.getLegend().setItemFont(font);
		
		CategoryPlot plot = (CategoryPlot)chart.getPlot(); 
		plot.setNoDataMessage("无统计数据");
		CategoryAxis domainAxis = plot.getDomainAxis();  
		domainAxis.setLabelFont(font); 
		domainAxis.setTickLabelFont(font);  
		domainAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45);
		
        
		ValueAxis rangeAxis = plot.getRangeAxis();
		rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); 
		rangeAxis.setLabelFont(font);
		rangeAxis.setTickLabelFont(font);
		rangeAxis.setUpperMargin(10D);
		rangeAxis.setFixedAutoRange(0D);
		rangeAxis.setUpperBound(50D);
		return chart;
	}
	
	/**
	 * <li>@方法说明:获得饼图JFREECHART对象
	 * <li>@param reportVO
	 * <li>@return
	 * <li>@创建人:王剑
	 * <li>@创建日期:2010-7-26
	 * <li>@修改人: 
	 * <li>@修改日期:
	 * <li>@详细说明: 
	 */
	public static JFreeChart getPieChart(ReportSingleSerChartVO reportVO){
		Font font = new Font("宋体",Font.PLAIN,13);
		DefaultPieDataset data = new DefaultPieDataset();
		for (int i = 0; i <reportVO.getDataList().size(); i++) {
			ReportSingleSerDataVO dataVO =reportVO.getDataList().get(i);
			data.setValue(dataVO.getLabel(), StringUtil.Str3Num(dataVO.getValue()));
		}
		JFreeChart chart = ChartFactory.createPieChart(reportVO.getReportName(), data, true, true, false);
		
		chart.setTitle(new TextTitle(chart.getTitle().getText(),new Font("宋体",Font.PLAIN,20)));
		PiePlot pieplot = (PiePlot)chart.getPlot(); 
		pieplot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}=>{1}({2})",NumberFormat.getNumberInstance(),new DecimalFormat("0.00%")));
		pieplot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0}=>{1}({2})",NumberFormat.getNumberInstance(),new DecimalFormat("0.00%")));
		pieplot.setLabelFont(font); 
	    pieplot.setForegroundAlpha(0.5f);
	    pieplot.setBackgroundPaint(Color.white);
	    pieplot.setIgnoreZeroValues(false);
	    pieplot.setNoDataMessage("无统计数据");
	    chart.getLegend().setItemFont(font);
	    return chart;
	}
	
	/*public void setFileOutStr(ReportTableViewVO viewVO,String filePath){
		String fileName = filePath+"report_"+DateUtil.getNowDate("ddHHmmssSSS")+".xls";
		POIFManager _poif = POIFManager.createCell4T();
		_poif.iteratorValue4XLS(viewVO);
		_poif.writ2disk(fileName);
		viewVO.setFileOutStr(fileName);
	
	}
*/
	
	protected Map<String, Object> mentMap = new HashMap<String, Object>();
	public ReportTableViewVO getTableViewVO(HttpServletRequest req) throws ServiceException{
		ReportTableViewVO vo = new ReportTableViewVO();
		vo.setDataList(findDatas(req));

		vo.setTitleList(findTitles(req));
		vo.setMentList(findMents(req));
		
		List<ReportDataVO> datalist =  vo.getDataList();

		long allCount = 0l;
		
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Map<String, Object> titleMap = new HashMap<String, Object>();
		
		
		String titleCode = "小计";
		String mentCode = "合计";
		for (int i = 0; i < datalist.size(); i++) {
			ReportDataVO v = datalist.get(i);
			String ment = v.getMents();
			String title = v.getTitles();
			
			dataMap.put(title+"_"+ment, v.getCounts());
		}
		
		
		for (int i = 0; i < vo.getTitleList().size(); i++) {
			
			for (int j = 0; j < vo.getMentList().size(); j++) {
				ReportTitleVO t = vo.getTitleList().get(i);
				ReportTitleVO m = vo.getMentList().get(j);
				
				String ment = m.getCode();
				String title = t.getCode();
				String datakey = title+"_"+ment;
				Object counts = String.valueOf(dataMap.get(datakey));
				if(counts!=null&&!"null".equals(String.valueOf(counts))){
					allCount += Long.valueOf(String.valueOf(counts));
				}
				
				if(!StringUtil.isBlank(titleMap.get(title+"_"+mentCode))){
					long olddata = 0l;
					long tdata = 0l;
					if(titleMap.get(title+"_"+mentCode)!=null&&!"null".equals(String.valueOf(titleMap.get(title+"_"+mentCode)))){
						olddata = Long.valueOf(String.valueOf(titleMap.get(title+"_"+mentCode)));
					}
					if(!"null".equals(String.valueOf(counts))){
						tdata = Long.valueOf(String.valueOf(counts));
					}
					titleMap.put(title+"_"+mentCode, olddata+ tdata);
					
				}else{
					long tdata = 0l;
					if(!"null".equals(String.valueOf(counts))){
						tdata = Long.valueOf(String.valueOf(counts));
					}
					titleMap.put(title+"_"+mentCode,tdata);
				}
			}
		}
		for (int i = 0; i < vo.getMentList().size(); i++) {
			
			for (int j = 0; j < vo.getTitleList().size(); j++) {
				ReportTitleVO t = vo.getTitleList().get(j);
				ReportTitleVO m = vo.getMentList().get(i);
				
				String ment = m.getCode();
				String title = t.getCode();
				String datakey = title+"_"+ment;
				
				if(!StringUtil.isBlank(mentMap.get(titleCode+"_"+ment))){
					long olddata = 0l;
					long tdata = 0l;
					if(mentMap.get(titleCode+"_"+ment)!=null&&!"null".equals(String.valueOf(mentMap.get(titleCode+"_"+ment)))){
						olddata = Long.valueOf(String.valueOf(mentMap.get(titleCode+"_"+ment)));
					}
					if(!"null".equals(String.valueOf(dataMap.get(datakey)))){
						tdata = Long.valueOf(String.valueOf(dataMap.get(datakey)));
					}
					mentMap.put(titleCode+"_"+ment, olddata+ tdata);
					
				}else{
					long tdata = 0l;
					if(!"null".equals(String.valueOf(dataMap.get(datakey)))){
						tdata = Long.valueOf(String.valueOf(dataMap.get(datakey)));
					}
					mentMap.put(titleCode+"_"+ment,tdata);
				}
			}
		}
		
		
		
		dataMap.putAll(mentMap);
		dataMap.putAll(titleMap);
		dataMap.put("小计_合计", allCount);
		log.info("===getDataMap===");
		vo.setDataMap(dataMap);
		
		return vo;
	}
	
	
	public ReportTableViewVO getTableViewVO1(HttpServletRequest req) throws ServiceException{
		ReportTableViewVO vo = new ReportTableViewVO();
		vo.setDataList(findDatas(req));

		vo.setTitleList(findTitles(req));
		vo.setMentList(findMents(req));
		
		List<ReportDataVO> datalist =  vo.getDataList();

		long allCount = 0l;
		
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Map<String, Object> titleMap = new HashMap<String, Object>();
		
		
		String titleCode = "小计";
		String mentCode = "合计";
		for (int i = 0; i < datalist.size(); i++) {
			ReportDataVO v = datalist.get(i);
			String ment = v.getMents();
			String title = v.getTitles();
			
			dataMap.put(title+"_"+ment, v.getCounts());
			
			
			if(v.getCounts()!=null&&!"null".equals(String.valueOf(v.getCounts()))){
				allCount += Long.valueOf(String.valueOf(v.getCounts()));
			}
			
			//列集合
		
			if(!StringUtil.isBlank(titleMap.get(title+"_"+mentCode))){
				long olddata = 0l;
				long tdata = 0l;
				if(titleMap.get(title+"_"+mentCode)!=null&&!"null".equals(String.valueOf(titleMap.get(title+"_"+mentCode)))){
					olddata = Long.valueOf(String.valueOf(titleMap.get(title+"_"+mentCode)));
				}
				if(!"null".equals(String.valueOf(v.getCounts()))){
					tdata = Long.valueOf(String.valueOf(v.getCounts()));
				}
				titleMap.put(title+"_"+mentCode, olddata+ tdata);
				
			}else{
				long tdata = 0l;
				if(!"null".equals(String.valueOf(v.getCounts()))){
					tdata = Long.valueOf(String.valueOf(v.getCounts()));
				}
				titleMap.put(title+"_"+mentCode,tdata);
				
			}
			
			
			
			if(!StringUtil.isBlank(mentMap.get(titleCode+"_"+ment))){
				
				long olddata = 0l;
				long tdata = 0l;
				if(!"null".equals(String.valueOf(mentMap.get(titleCode+"_"+ment)))){
					olddata = Long.valueOf(String.valueOf(mentMap.get(titleCode+"_"+ment)));
				}
				if(!"null".equals(String.valueOf(v.getCounts()))){
					tdata = Long.valueOf(String.valueOf(v.getCounts()));
				}
				mentMap.put(titleCode+"_"+ment, olddata+ tdata);
			}else{
				long tdata = 0l;
				if(!"null".equals(String.valueOf(v.getCounts()))){
					tdata = Long.valueOf(String.valueOf(v.getCounts()));
				}
				mentMap.put(titleCode+"_"+ment,tdata);
				
			}
		}
		
		dataMap.putAll(mentMap);
		dataMap.putAll(titleMap);
		dataMap.put("小计_合计", allCount);
		log.info("===getDataMap===");
		vo.setDataMap(dataMap);
		
		return vo;
	}
	
	/**
	 * <li>@方法说明:多序列对象
	 * <li>@param costom
	 * <li>@param paramVOList
	 * <li>@param labelName
	 * <li>@param valueName
	 * <li>@param seriesName 不为空时，为多序列对象,序列名为运算序列
	 * <li>@param serName 不为空时，单序列对象，且只有一个名
	 * <li>@return
	 * <li>@throws ServiceException
	 * <li>@创建人:王剑
	 * <li>@创建日期:2010-7-10
	 * <li>@修改人: 
	 * <li>@修改日期:
	 * <li>@详细说明: 
	 */
/*	public ReportSingleSerChartVO getReportVO(ReportTableViewVO viewVO) throws ServiceException{
		try {
			ReportSingleSerChartVO reportVO = new ReportSingleSerChartVO();
			reportVO.setReportName(viewVO.getReportName());
			List<Hashtable> hashList = viewVO.getDataList();
			List<ReportSingleSerDataVO> dataList = new ArrayList<ReportSingleSerDataVO>();
			for(int i=0;i<hashList.size();i++){
				ReportSingleSerDataVO dataVO = new ReportSingleSerDataVO();
				Hashtable vo = hashList.get(i);
				if(!StringUtil.isBlank(viewVO.getSeriesName())){
					dataVO.setSeriesName((String) vo.get(viewVO.getSeriesName()));
				}
				else if(!StringUtil.isBlank(viewVO.getSerName())){
					dataVO.setSeriesName(viewVO.getSerName());
				}
				dataVO.setLabel((String) vo.get("names"));
				dataVO.setValue(String.valueOf(((Long)vo.get("counts")).longValue()));
				dataList.add(dataVO);
			}
			reportVO.setDataList(dataList);
			return reportVO;
		} catch (Exception e) {
			log.error(e.getMessage());
			throw new ServiceException(e);
		}
	}*/
	
	
/*	
	public JFreeChart getBarChartVO(ReportTableViewVO viewVO) throws ServiceException {
		return getBarChart(getReportVO(viewVO));
	}

	public JFreeChart getLineChartVO(ReportTableViewVO viewVO) throws ServiceException {
		return getLineChart(getReportVO(viewVO));
	}

	public JFreeChart getPieChartVO(ReportTableViewVO viewVO) throws ServiceException {
		return getPieChart(getReportVO(viewVO));
	}*/
	//	须实现方法
	public abstract List<ReportDataVO> findDatas(HttpServletRequest req) throws ServiceException;
	public abstract List<ReportTitleVO> findTitles(HttpServletRequest req) throws ServiceException;
	public abstract List<ReportTitleVO> findMents(HttpServletRequest req) throws ServiceException;
	//public abstract ReportSingleSerChartVO getReportChartVO(ReportTableViewVO viewVO) throws ServiceException;

	public String getEndDate() {
		return endDate;
	}

	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	public String getStartDate() {
		return startDate;
	}

	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	public String getYear() {
		return year;
	}

	public void setYear(String year) {
		this.year = year;
	}

	public String getYearMonth() {
		return yearMonth;
	}

	public void setYearMonth(String yearMonth) {
		this.yearMonth = yearMonth;
	}

	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}
	
}
